package cn.edu.dgut.sai.json;

import cn.edu.dgut.sai.database.jdbc.DBUtil;
import org.omg.PortableInterceptor.SYSTEM_EXCEPTION;

import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.time.LocalDate;
import java.util.stream.Collectors;

/**
 * @author Sai
 * Created by Sai on 2019-03-15.
 */
@WebServlet(urlPatterns = {"/json"})
public class JsonServlet extends HttpServlet {

    // curl -v http://localhost:8080/webapp-demo/json
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    }


    // 获取前端post提交的json字符串，并转换为对象；再把对象转为json字符串，生成响应返回前端。
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            // 接收post请求的学生信息
            Jsonb jsonb = JsonbBuilder.create();
            String postJsonString = new BufferedReader(new InputStreamReader(req.getInputStream()))
                    .lines().collect(Collectors.joining(System.lineSeparator()));

            // 注意：重新编码字符串为utf-8码
            postJsonString = new String(postJsonString.getBytes(),"utf-8");

            // 利用jsonb把json字符串转换为对象
            StudentDTO studentDTO = jsonb.fromJson(postJsonString, StudentDTO.class);
            resp.setContentType("application/json");
            resp.setCharacterEncoding("UTF-8");
            // 获取h2数据库连接
            Connection connection = DBUtil.getConnection();
            PreparedStatement ps = null;
            String sql = "insert into `student` (stuID,stuName,stuClass,stuGender) values (?,?,?,?)";
            ps = connection.prepareStatement(sql);
            ps.setInt(1,studentDTO.getStuID());
            ps.setString(2,studentDTO.getStuName());
            ps.setString(3,studentDTO.getStuClass());
            ps.setString(4,studentDTO.getStuGender());
            // 如果插入成功则返回成功json信息，否则返回失败信息
            if(ps.executeUpdate() == 1){
                // 创建一个返回的JSON对象
                ResponseDTO responseDTO = new ResponseDTO(0,"操作成功");
                // 要获取对象的JSON表示，我们需要使用JsonbBuilder类及其toJson（）方法。
                Jsonb json = JsonbBuilder.create();
                String jsonPerson = json.toJson(responseDTO);
                System.out.println("json：" + jsonPerson);
                resp.setContentType("application/json");
                resp.setCharacterEncoding("UTF-8");
                resp.getWriter().println(jsonPerson);
            }else {
                // 创建一个返回的JSON对象
                ResponseDTO responseDTO = new ResponseDTO(1,"操作失败");
                // 要获取对象的JSON表示，我们需要使用JsonbBuilder类及其toJson（）方法。
                Jsonb json = JsonbBuilder.create();
                String jsonPerson = json.toJson(responseDTO);
                System.out.println("json：" + jsonPerson);
                resp.setContentType("application/json");
                resp.setCharacterEncoding("UTF-8");
                resp.getWriter().println(jsonPerson);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
